#!/usr/bin/env python2.7

# peak_util.py

import os, sys
#import re
#from datetime import datetime, timedelta
#from dateutil.parser import parse
import numpy as np
#import matplotlib
#matplotlib.use('Agg')
#import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap
#from matplotlib import mlab
#from netCDF4 import Dataset
from copy import copy, deepcopy
from metlib.lidar.peak import *

def remove_small_valleys(peaks_list):
    all_depths = []
    for peaks in peaks_list:
        for p in peaks:
            if p.sign == -1:
                all_depths.append(-p.depth)
    all_depths.sort()
    n_depths = len(all_depths)
    depth_thres = np.mean(all_depths[int(0.25 * n_depths):int(0.75 * n_depths)]) * 0.5
    nosmall_list = []
    for peaks in peaks_list:
        tmp_peaks = []
        for p in peaks:
            if p.sign == -1:
                if -p.depth >= depth_thres:
                    tmp_peaks.append(p)
            else:
                tmp_peaks.append(p)
        nosmall_list.append(tmp_peaks)
    return nosmall_list

def remove_high_peaks(peaks_list, max_index):
    low_list = []
    for peaks in peaks_list:
        temp_peaks = filter(lambda p: p.center <= max_index, peaks)
        low_list.append(temp_peaks)
    return low_list
    
def keep_largest_valleys(peaks_list, number=2):
    onlylarge_list = []
    for peaks in peaks_list:
        negs = []
        poss = []
        for p in peaks:
            if p.sign == -1: 
                negs.append(p)
            else:
                poss.append(p) 
        negs.sort(key=lambda p: p.depth)
        largest_negs = negs[0:number]
        negpos = largest_negs + poss
        negpos.sort(key=lambda p: p.center)
        onlylarge_list.append(negpos)
    return onlylarge_list

def join_near_valleys(peaks_list, dist_thres=4):
    joined_list = []
    for peaks in peaks_list:
        tmp_peaks = []
        n_peak = len(peaks)
        i = 0 
        while i < n_peak-1: 
            if peaks[i].sign == -1 and peaks[i+1].sign == -1 and (peaks[i+1].center - peaks[i].center) <= dist_thres:
                tmp_pair = [peaks[i], peaks[i+1]]
                tmp_pair.sort(key=lambda p: p.depth)
                new_peak = copy(tmp_pair[0])
                new_peak.lower = np.min([p.lower for p in tmp_pair])
                new_peak.upper = np.max([p.upper for p in tmp_pair])
                tmp_peaks.append(new_peak)
                i += 2
            else:
                tmp_peaks.append(peaks[i])
                i += 1
        if i == n_peak-1:
            tmp_peaks.append(peaks[i])
        joined_list.append(tmp_peaks)
    return joined_list

